import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Typography, Tag, Spin, Empty, Button, Statistic, message } from 'antd';
import { 
  ShopOutlined, EyeOutlined, StarOutlined, FireOutlined, 
  RocketOutlined, CalendarOutlined 
} from '@ant-design/icons';
import { categoryService } from '@/services';
import { Category, CategoryStats, CategoryStatus } from '@/types/category';
import { history } from '@umijs/max';

const { Title } = Typography;

const CategoriesPage: React.FC = () => {
  const [categories, setCategories] = useState<Category[]>([]);
  const [categoryStats, setCategoryStats] = useState<CategoryStats[]>([]);
  const [loading, setLoading] = useState(true);
  const [statsLoading, setStatsLoading] = useState(true);
  
  const navigate = history;

  useEffect(() => {
    loadCategories();
    loadCategoryStats();
  }, []);

  const loadCategories = async () => {
    try {
      setLoading(true);
      const categoriesData = await categoryService.getCategories({ 
        status: CategoryStatus.ENABLED, 
        level: 1 
      });
      setCategories(categoriesData);
    } catch (error) {
      message.error('加载分类失败');
      console.error('分类加载错误:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadCategoryStats = async () => {
    try {
      setStatsLoading(true);
      const stats = await categoryService.getCategoryStats();
      setCategoryStats(stats);
    } catch (error) {
      console.error('分类统计加载错误:', error);
    } finally {
      setStatsLoading(false);
    }
  };

  const handleCategoryClick = (category: Category) => {
    navigate(`/search?category=${category.id}&q=${encodeURIComponent(category.name)}`);
  };

  const getCategoryStats = (categoryId: string) => {
    return categoryStats.find(stat => (stat as any).categoryId === categoryId);
  };

  const getCategoryIcon = (categoryId: string): string => {
    const icons: Record<string, string> = {
      'electronics': '📱',
      'books': '📚',
      'clothing': '👕',
      'daily': '🏠',
      'sports': '⚽'
    };
    return icons[categoryId] || '📦';
  };

  const getCategoryColor = (categoryId: string): string => {
    const colors: Record<string, string> = {
      'electronics': 'blue',
      'books': 'green',
      'clothing': 'orange',
      'daily': 'purple',
      'sports': 'red'
    };
    return colors[categoryId] || 'gray';
  };

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      {/* 页面标题 */}
      <div className="text-center mb-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-2">分类浏览</h1>
        <p className="text-gray-600">按分类浏览校园二手商品，快速找到您需要的物品</p>
      </div>

      {/* 分类统计概览 */}
      <Card className="shadow-sm border-0 mb-8">
        <Title level={4} className="text-gray-900 mb-6">
          <ShopOutlined className="mr-2" />分类概览
        </Title>
        
        {statsLoading ? (
          <div className="text-center py-4">
            <Spin size="small" />
            <div className="text-gray-500 text-sm mt-2">加载统计信息...</div>
          </div>
        ) : categoryStats.length > 0 ? (
          <Row gutter={[16, 16]}>
            {categoryStats.slice(0, 6).map(stat => (
              <Col xs={12} sm={8} lg={4} key={stat.categoryId}>
                <Card 
                  size="small" 
                  className="text-center border-0 hover:shadow-md transition-shadow"
                >
                  <Statistic
                    title={(stat as any).categoryName}
                    value={stat.totalProducts}
                    prefix={<ShopOutlined />}
                    valueStyle={{ color: getCategoryColor((stat as any).categoryId) }}
                  />
                  <div className="text-xs text-gray-500 mt-2">
                    成交率: {(stat as any).successRate}%
                  </div>
                </Card>
              </Col>
            ))}
          </Row>
        ) : (
          <Empty description="暂无分类统计信息" />
        )}
      </Card>

      {/* 分类浏览 */}
      <Card className="shadow-sm border-0">
        <Title level={4} className="text-gray-900 mb-6">
          <EyeOutlined className="mr-2" />全部分类
        </Title>
        
        {loading ? (
          <div className="text-center py-12">
            <Spin size="large" />
            <div className="text-gray-500 mt-4">加载分类中...</div>
          </div>
        ) : categories.length > 0 ? (
          <Row gutter={[24, 24]}>
            {categories.map(category => {
              const stats = getCategoryStats(category.id);
              
              return (
                <Col xs={24} sm={12} lg={8} key={category.id}>
                  <Card 
                    hoverable
                    className="h-full border-0 shadow-sm hover:shadow-md transition-all"
                    onClick={() => handleCategoryClick(category)}
                  >
                    <div className="flex items-start mb-4">
                      <div className="text-4xl mr-4">{getCategoryIcon(category.id)}</div>
                      <div className="flex-1">
                        <h3 className="text-xl font-semibold text-gray-900 mb-2">
                          {category.name}
                        </h3>
                        <p className="text-gray-600 text-sm mb-3">
                          {category.description}
                        </p>
                        
                        {stats && (
                          <div className="grid grid-cols-3 gap-2 text-xs">
                            <div className="text-center">
                              <div className="font-medium text-blue-600">{stats.totalProducts}</div>
                              <div className="text-gray-500">商品数</div>
                            </div>
                            <div className="text-center">
                              <div className="font-medium text-green-600">{stats.successRate}%</div>
                              <div className="text-gray-500">成交率</div>
                            </div>
                            <div className="text-center">
                              <div className="font-medium text-orange-600">{stats.weeklyGrowth}%</div>
                              <div className="text-gray-500">周增长</div>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                    
                    <div className="flex justify-between items-center">
                      <Tag 
                        color={getCategoryColor(category.id)}
                        className="rounded-full"
                      >
                        {(category as any).productCount || 0} 件商品
                      </Tag>
                      
                      <Button 
                        type="link" 
                        size="small" 
                        className="text-blue-600 hover:text-blue-700"
                      >
                        浏览更多 →
                      </Button>
                    </div>
                  </Card>
                </Col>
              );
            })}
          </Row>
        ) : (
          <Empty description="暂无分类数据" />
        )}
      </Card>

      {/* 热门分类推荐 */}
      <Card className="shadow-sm border-0 mt-8">
        <Title level={4} className="text-gray-900 mb-6">
          <FireOutlined className="mr-2" />热门分类推荐
        </Title>
        
        {!statsLoading && categoryStats.length > 0 && (
          <Row gutter={[16, 16]}>
            {categoryStats
              .filter(stat => (stat as any).weeklyGrowth > 5)
              .slice(0, 3)
              .map(stat => (
                <Col xs={24} md={8} key={(stat as any).categoryId}>
                  <div className="p-4 bg-gradient-to-r from-orange-50 to-red-50 rounded-lg border border-orange-100">
                    <div className="flex items-center mb-2">
                      <RocketOutlined className="text-orange-500 text-lg mr-2" />
                      <span className="font-semibold text-orange-700">热门分类</span>
                    </div>
                    <h4 className="text-lg font-medium text-gray-900 mb-1">
                      {(stat as any).categoryName}
                    </h4>
                    <div className="flex justify-between text-sm text-gray-600">
                      <span>商品数: {(stat as any).totalProducts}</span>
                      <span>周增长: +{(stat as any).weeklyGrowth}%</span>
                    </div>
                    <Button 
                      type="link" 
                      size="small" 
                      className="text-orange-600 hover:text-orange-700 mt-2 p-0"
                      onClick={() => navigate(`/search?category=${(stat as any).categoryId}`)}
                    >
                      立即查看 →
                    </Button>
                  </div>
                </Col>
              ))}
          </Row>
        )}
        
        {!statsLoading && categoryStats.filter(stat => stat.weeklyGrowth > 5).length === 0 && (
          <div className="text-center py-6 text-gray-500">
            <CalendarOutlined className="text-3xl mb-2" />
            <div>暂无热门分类推荐</div>
          </div>
        )}
      </Card>
    </div>
  );
};

export default CategoriesPage;